#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
论文查重系统打包脚本
使用PyInstaller将Kivy应用打包成独立可执行文件
"""

import os
import sys
import subprocess
import shutil

def check_dependencies():
    """检查必要的依赖是否已安装"""
    try:
        import PyInstaller
        print("PyInstaller已安装")
    except ImportError:
        print("PyInstaller未安装，正在安装...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
            print("PyInstaller安装成功")
        except Exception as e:
            print(f"PyInstaller安装失败: {e}")
            return False
    
    try:
        import kivy
        print("Kivy已安装")
    except ImportError:
        print("Kivy未安装，请先安装Kivy")
        return False
    
    return True

def create_spec_file():
    """创建PyInstaller spec配置文件"""
    spec_content = '''# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['paper_checker_chinese_optimized.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('complex_paper_airplane_icon.png', '.'),
        ('paper_titles_unified.json', '.'),
        ('faiss_index_unified.bin', '.'),
        ('best_parameters.json', '.'),
        ('validation_dataset.json', '.'),
    ],
    hiddenimports=[
        'kivy',
        'faiss',
        'jieba',
        'Levenshtein',
        'sentence_transformers',
        'numpy',
        'core_elements_utils',
        'jieba.analyse',
        'csv',
        'datetime',
        'threading',
        'os',
        'typing',
        'json',
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='论文查重系统',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='complex_paper_airplane_icon.png'
)
'''
    
    with open('paper_checker_system.spec', 'w', encoding='utf-8') as f:
        f.write(spec_content)
    
    print("已创建打包配置文件: paper_checker_system.spec")

def build_executable():
    """执行打包操作"""
    try:
        print("开始打包...")
        # 使用Python模块方式调用PyInstaller
        subprocess.check_call([sys.executable, '-m', 'PyInstaller', 'paper_checker_system.spec'])
        print("打包完成！")
        print("可执行文件位于 dist/论文查重系统/ 目录下")
        return True
    except subprocess.CalledProcessError as e:
        print(f"打包过程中出现错误: {e}")
        return False
    except FileNotFoundError as e:
        print(f"找不到PyInstaller: {e}")
        print("请确保PyInstaller已正确安装")
        return False

def main():
    """主函数"""
    print("论文查重系统打包工具")
    print("=" * 30)
    
    # 检查依赖
    if not check_dependencies():
        print("依赖检查失败，请先安装必要的依赖")
        return
    
    # 创建spec文件
    create_spec_file()
    
    # 执行打包
    if build_executable():
        print("\\n打包成功！")
        print("您可以在 dist/论文查重系统/ 目录下找到可执行文件")
        print("将整个目录分发给其他用户即可运行，无需安装Python环境")
    else:
        print("\\n打包失败，请检查错误信息")

if __name__ == "__main__":
    main()